import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import router from 'umi/router';
import {
  queryVIPUserManagementDetail,
  queryDiscountList,
  updateVipUser,
  saveVipUser,
  queryDiscountData,
  performDeleteDiscount,
} from './service';

import { fetchValidation } from '@/utils';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchDiscountList: Effect;
    saveAndUpdate: Effect;
    fetchDiscountDetail: Effect;
    deleteDiscount: Effect;
  };
  reducers: {
    save: Reducer;
    saveData: Reducer;
    saveDetailData: Reducer;
    clear: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'VIPUserManagementDiscount',

  state: {
    detailInfo: {},
    dataInfo: {
      count: 0,
      list: [],
    },
    discountDetailInfo: {},
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryVIPUserManagementDetail, payload);
      yield put({
        type: 'save',
        payload: response.body,
      });
    },

    * fetchDiscountList({ payload }, { call, put }) {
      const response = yield call(queryDiscountList, payload);
      yield put({
        type: 'saveData',
        payload: response.body || { count: 0, list: [] },
      });
    },

    * fetchDiscountDetail({ payload }, { call, put }) {
      const response = yield call(queryDiscountData, payload);
      yield put({
        type: 'saveDetailData',
        payload: response.body,
      });
    },

    * saveAndUpdate({ payload: { searchValue, query } }, { call, put }) {
      const response = yield call((query.id ? updateVipUser : saveVipUser), query);
      const data = fetchValidation(response);
      if (data) {
        message.success(query.id ? '修改成功!' : '添加成功!');
        yield put({
          type: 'fetchDiscountList',
          payload: searchValue,
        });
      }
    },

    * deleteDiscount({ payload }, { call, put }) {
      const response = yield call(performDeleteDiscount, payload);
      /* const data = fetchValidation(response);
      if (data) {
        message.success('删除成功');
      } */
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        detailInfo: action.payload,
      };
    },

    saveData(state, action) {
      return ({
        ...state,
        dataInfo: action.payload,
      });
    },

    saveDetailData(state, action) {
      return ({
        ...state,
        discountDetailInfo: action.payload,
      });
    },

    clear(state) {
      return ({
        ...state,
        discountDetailInfo: {},
      });
    },
  },
};

export default Model;
